package ln.gather.jsr.jcache.integration;

import javax.cache.Cache;
import javax.cache.integration.CacheLoaderException;
import javax.cache.integration.CacheWriterException;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

public abstract class AbstractFallbackStorage<K,V> implements FallbackStorage<K,V>{

    private final int priority;

    public AbstractFallbackStorage(int priority) {
        this.priority = priority;
    }

    @Override
    public int getPriority() {
        return priority;
    }

    /**
     * 通用实现，子类无需再实现
     * @param keys keys identifying the values to be loaded
     * @return
     * @throws CacheLoaderException
     */
    @Override
    public Map<K, V> loadAll(Iterable<? extends K> keys) throws CacheLoaderException {
        Map<K, V> map = new LinkedHashMap<>();
        keys.forEach(key -> {
            map.put(key, load(key));
        });
        return map;
    }

    /**
     * 通用实现，子类无需再实现
     * @param entries a mutable collection to write. Upon invocation, it contains
     *                the entries to write for write-through. Upon return the
     *                collection must only contain entries that were not
     *                successfully written. (see partial success above)
     * @throws CacheWriterException
     */
    @Override
    public void writeAll(Collection<Cache.Entry<? extends K, ? extends V>> entries) throws CacheWriterException {
        entries.forEach(this::write);
    }

    /**
     * 通用实现，子类无需再实现
     * @param keys a mutable collection of keys for entries to delete. Upon
     *             invocation, it contains the keys to delete for write-through.
     *             Upon return the collection must only contain the keys that were
     *             not successfully deleted. (see partial success above)
     * @throws CacheWriterException
     */
    @Override
    public void deleteAll(Collection<?> keys) throws CacheWriterException {
        keys.forEach(this::delete);
    }
}
